import BGMManager from "../../../../core/bgm_manager";
import data from "../../../../core/cache_data";
import { ReplacePageAni } from "../../../../core/game";
import Utils, { Random } from "../../../../core/utils";
import EggyReadyItem from "../../../eggy/assets/eggy_ready_item";
import { Fight, FightConfig } from "../../game/fight";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PageReady extends cc.Component {
    _blocked = false;

    @property(cc.Node)
    container: cc.Node = null;

    @property(cc.Prefab)
    readyItemPrefab: cc.Prefab = null;

    protected onEnable(): void {
        BGMManager.ins.addGrille("page_ready", 0.4);
    }
    protected onDisable(): void {
        BGMManager.ins.delGrille("page_ready");
    }

    protected onLoad(): void {
        let fight: Fight = data.storage.get("fight", null);
        if (fight) {
            fight.characters.forEach(charData => {
                let item = cc.instantiate(this.readyItemPrefab).getComponent(EggyReadyItem);
                item.char = charData;
                this.container.addChild(item.node);
            })
        }
    }

    onClickAdd() {
        let item = cc.instantiate(this.readyItemPrefab).getComponent(EggyReadyItem);
        this.container.addChild(item.node);
    }

    onClickStart() {
        if (this._blocked) {
            return;
        }
        this._blocked = true;

        let fight = new Fight();
        let conf = new FightConfig();
        FightConfig.AssignUniqueObject(fight, conf);

        this.container.getComponentsInChildren(EggyReadyItem).forEach(item => {
            fight.characters.push(item.char);
        });
        fight.data.time = Random.range(5, 10);
        data.cache.set("fight", fight);

        Utils.game.resReplacePage({
            name: "page_game",
            ani: ReplacePageAni.Fade
        });

        data.storage.set("fight", fight);
    }
}
